package com.hzjob.util;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class MySessionFactory {

	private static SessionFactory sessionFactory;
	private final static ThreadLocal<Session> localThreads = new ThreadLocal<Session>();

	public static Session currentSession(int sessionFactoryId) {
		Session session = (Session) localThreads.get();
		if (session == null) {
			if (sessionFactory == null) {
				if (1 == sessionFactoryId) {
					sessionFactory = new Configuration().configure().buildSessionFactory();
					session = sessionFactory.openSession();
					localThreads.set(session);
				} else if (2 == sessionFactoryId) {
					sessionFactory = new Configuration().configure("one2one/hibernate.cfg.xml").buildSessionFactory();
					session = sessionFactory.openSession();
					localThreads.set(session);
				}
			} else {
				session = sessionFactory.openSession();
				localThreads.set(session);
			}
		}
		return session;
	}

	public static void closeSession() {
		Session session = (Session) localThreads.get();
		if (session != null) {
			session.close();
			localThreads.set(null);
		}
	}

}
